/*
 * Copyright (C) 2025 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

extern crate alloc;

use alloc::boxed::Box;
use crate::Vec;

use crate::common::constants::ErrorCode;
use crate::common::types::Uuid;
use crate::entry::user_auth_ffi::CommandId;
use crate::log_e;
use crate::singleton_registry;

pub enum Caller {
    Ca,
    Ta(Uuid),
}

pub enum AccessPolicy {
    AllowCaAccess,
    AllowTaAccess(Vec<Uuid>),
    AllowCaAndTaAccess(Vec<Uuid>),
}

impl AccessPolicy {
    pub fn is_access_allowed(&self, caller: &Caller) -> bool {
        match (self, caller) {
            (AccessPolicy::AllowCaAccess, Caller::Ca) => true,
            (AccessPolicy::AllowTaAccess(allowed_uuids), Caller::Ta(uuid)) => {
                allowed_uuids.contains(uuid)
            }
            (AccessPolicy::AllowCaAndTaAccess(_), Caller::Ca) => true,
            (AccessPolicy::AllowCaAndTaAccess(allowed_uuids), Caller::Ta(uuid)) => {
                allowed_uuids.contains(uuid)
            }
            _ => false,
        }
    }
}

pub trait CommandHandler {
    fn command_id(&self) -> &CommandId;
    fn access_policy(&self) -> &AccessPolicy;
    fn handle(&self, input: &[u8], output: &mut [u8]) -> Result<(), ErrorCode>;
}

pub trait CommandManager {
    fn register(&mut self, command_handler: Box<dyn CommandHandler>) -> Result<(), ErrorCode>;
    fn get<'a>(&'a self, command_id: CommandId) -> Result<&'a Box<dyn CommandHandler>, ErrorCode>;
}

pub struct DummyCommandManager;

impl CommandManager for DummyCommandManager {
    fn register(&mut self, _command: Box<dyn CommandHandler>) -> Result<(), ErrorCode> {
        log_e!("not implemented");
        Err(ErrorCode::GeneralError)
    }

    fn get<'a>(&'a self, _command_id: CommandId) -> Result<&'a Box<dyn CommandHandler>, ErrorCode> {
        log_e!("not implemented");
        Err(ErrorCode::GeneralError)
    }
}

singleton_registry!(CommandManagerRegistry, CommandManager, DummyCommandManager);
